import {Component, OnInit} from '@angular/core';
import {HireDeviceService} from '../hireDevice.service';
import {DatePipe} from '@angular/common';
import {UsedStorePService} from '../../used-store/used-store-p.service';
import {NzMessageService} from 'ng-zorro-antd/message';
import {NzUploadFile} from 'ng-zorro-antd/upload';
import {HttpClient} from '@angular/common/http';
import {NzModalService} from 'ng-zorro-antd/modal';
import {CommonService} from '../../../services-common/common.service';


@Component({
  selector: 'app-order',
  templateUrl: './order.component.html',
  styleUrls: ['./order.component.scss']
})
export class OrderComponent implements OnInit {
  query = {
    orderNum: '', // 订单流水号
    title: '', // 商品标题
    goodsName: '', // 商品名称
    status: '', // 订单状态 多个用逗号隔开
    planId: [], // 租赁方案 多个用逗号隔开
    rper: [], // 租期 多个用逗号隔开
    user: '', // 用户信息
    date: [], // 下单时间
    page: 1,
    pageSize: 10,
  };
  // 表格数据
  listOfData = {
    page: 1,
    total: 100,
    records: []
  };
  statusNum: any = {};
  hireDateList = [];
  // 实付款
  realPayModal = {
    visible: false,
    list: [],
  };
  // 租金
  rentModal = {
    visible: false,
    list: [],
  };

  logistics: any[] = [];
  // 发货
  deliverGoodsModal = {
    visible: false,
    expressVas: 1,
    expressName: '',
    expressCode: '',
    expressNum: '',
    id: '',
    imei: '',
  };
  // 物流信息
  expressModal = {
    visible: false,
    expressList: [] as any,
    currentExpressNum: '',
    current: {} as any,
  };
  // 取消订单
  cancelOrderModal = {
    visible: false,
    id: '',
    cancelNote: '',
  };
  // 跟进
  trackModal: any = {
    visible: false,
    loading: false,
    id: '',
    url: '',
    remark: '',
    file: [],
  };
  // 审核
  checkModal: any = {
    visible: false,
    id: '',
    deductWay: 0,
    imei: '',
    wper: 1,
    nper: '', // 总期数
    firstRent: '', // 首期租金
    totalRent: '', // 总租金
  };
  // 租户凭证
  tenantModal = {
    visible: false,
    userCertInfo: {} as any,
  };
  // 交易快照
  snapshotModal = {
    visible: false,
    data: {} as any,
  };
  trackList: any[] = [];
  beforeUpload = (file: NzUploadFile): boolean => {
    const acceptFileType = [
      'bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif',
      'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps',
      'ai', 'raw', 'WMF', 'webp', 'avif', 'apng', 'pdf', 'txt',
      'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx',
    ];
    const fileName: any = file.name.split('.').pop();
    if (!acceptFileType.includes(fileName)) {
      this.nzMessageService.warning('暂不支持该文件类型');
      return false;
    }
    // @ts-ignore
    this.trackModal.file = [file];
    return false;
  };

  constructor(
    public hireDeviceService: HireDeviceService,
    private datePipe: DatePipe,
    private usedStorePService: UsedStorePService,
    private nzMessageService: NzMessageService,
    private httpClient: HttpClient,
    private nzModalService: NzModalService,
    private commonService: CommonService,
  ) {
  }

  async ngOnInit() {
    await this.hireDeviceService.getDict('hire_device_date').then((res: any) => {
      if (res.code === 0) {
        this.hireDateList = JSON.parse(res.data.content);
      }
    });
    await this.usedStorePService.dictData('logistics_company').then((res: any) => {
      if (res.code === 0) {
        this.logistics = res.data.list.records;
      }
    });
    this.getTableData();
  }


  onPageIndexChange(index: number) {
    this.query.page = index;
    this.getTableData();
  }

  onPageSizeChange(pageSize: number) {
    this.query.pageSize = pageSize;
    this.getTableData();
  }

  queryBtn() {
    this.query.page = 1;
    this.getTableData();
  }

  resetCondition() {
    this.query = {
      orderNum: '', // 订单流水号
      title: '', // 商品标题
      goodsName: '', // 商品名称
      status: '', // 订单状态 多个用逗号隔开
      planId: [], // 租赁方案 多个用逗号隔开
      rper: [], // 租期 多个用逗号隔开
      user: '', // 用户信息
      date: [], // 下单时间
      page: 1,
      pageSize: 10,
    };
    this.getTableData();
  }

  getTableData() {
    this.hireDeviceService.getOrderList({
      orderNum: this.query.orderNum, // 订单流水号
      title: this.query.title, // 商品标题
      goodsName: this.query.goodsName, // 商品名称
      status: this.query.status, // 订单状态 多个用逗号隔开
      planId: this.query.planId.join(','), // 租赁方案 多个用逗号隔开
      rper: this.query.rper.join(','), // 租期 多个用逗号隔开
      user: this.query.user, // 用户信息
      beginTime: this.datePipe.transform(this.query.date[0], 'yyyy-MM-dd') || '', // 下单开始时间
      endTime: this.datePipe.transform(this.query.date[1], 'yyyy-MM-dd') || '', // 下单结束时间
      page: this.query.page,
      pageSize: this.query.pageSize,
    }).then((res: any) => {
      if (res.code === 0) {
        this.listOfData = res.data.list;
        this.statusNum = res.data.map;
      }
      console.log(res);
    });
  }

  // 顶部分类切换
  tabClick(status: any) {
    this.query.status = status;
    this.query.page = 1;
    this.getTableData();
  }


  // 实付款明细显示
  showRealPayModal(list: any) {
    if (!list || !list.length) {
      this.nzMessageService.warning('没有找到相关记录');
      return;
    }
    this.realPayModal = {
      visible: true,
      list,
    };
  }

  // 实付款明细隐藏
  hideRealPayModal() {
    this.realPayModal = {
      visible: false,
      list: [],
    };
  }

  // 租金记录显示
  showRentModal(list: any) {
    if (!list || !list.length) {
      this.nzMessageService.warning('没有找到相关记录');
      return;
    }
    this.rentModal = {
      visible: true,
      list,
    };
  }

  // 租金记录隐藏
  hideRentModal() {
    this.rentModal = {
      visible: false,
      list: [],
    };
  }

  // 发货显示
  showDeliverGoodsModal(id: any) {
    this.deliverGoodsModal.visible = true;
    this.deliverGoodsModal.id = id;
  }

  // 发货隐藏
  hideDeliverGoodsModal() {
    this.deliverGoodsModal = {
      visible: false,
      expressVas: 1,
      expressName: '',
      expressCode: '',
      expressNum: '',
      id: '',
      imei: '',
    };
  }

  // 显示物流信息
  showExpressDetail(data: any) {
    if (!data.mallOrderExpressList?.length) {
      this.nzMessageService.error('没有找到物流信息');
      return;
    }
    this.expressModal.visible = true;
    this.expressModal.expressList = data.mallOrderExpressList.map((item: any) => ({
      ...item,
      expressTraces: JSON.parse(item.expressTraces)
    }));
    this.expressModal.currentExpressNum = this.expressModal.expressList[0].id;
    this.expressModal.current = this.expressModal.expressList[0];
  }

  // 隐藏物流信息
  hideExpressModal() {
    this.expressModal = {
      visible: false,
      expressList: [],
      currentExpressNum: '',
      current: {},
    };
  }

  // 物流单号改变
  currentExpressChange() {
    this.expressModal.current = this.expressModal.expressList.filter((item: any) => item.id === this.expressModal.currentExpressNum)[0];
  }

  // 显示取消订单
  showCancelOrderModal(id: any) {
    this.cancelOrderModal = {
      visible: true,
      id,
      cancelNote: '',
    };
  }

  // 隐藏取消订单
  hideCancelOrderModal() {
    this.cancelOrderModal = {
      visible: false,
      id: '',
      cancelNote: '',
    };
  }

  cancelOrder() {
    this.hireDeviceService.cancelOrder({id: this.cancelOrderModal.id, cancelNote: this.cancelOrderModal.cancelNote}).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.hideCancelOrderModal();
        this.getTableData();
      }
    });
  }

  showTrackModal(relationInformation: any) {
    this.trackModal.id = relationInformation;
    this.trackModal.visible = true;
    this.trackList = [];
    this.hireDeviceService.getTrackList({
      type: 13,
      relationInformation,
      page: 1,
      pageSize: 9999
    }).then((res: any) => {
      console.log(res);
      if (res.code === 0) {
        this.trackList = res.data.records;
        console.log(this.trackList);
      }
    });
    // this.ppypService.getTrackList(orderNum).then((resL: any) => {
    //   this.trackList = resL.data.records;
    // });
  }

  // 隐藏跟进模态框
  async hideTrackModal(submit: boolean) {
    if (submit) {
      if (!this.trackModal.remark) {
        this.nzMessageService.warning('请输入跟进内容');
        return;
      }
      this.trackModal.loading = true;
      if (this.trackModal.file.length) {
        const file = new FormData();
        file.append('file', this.trackModal.file[0]);
        file.append('name', (+new Date()).toString());
        await this.hireDeviceService.fileUpload(file).then((res: any) => {
          if (res.code === 0) {
            this.trackModal.url = res.data;
          }
        });
      }
      this.hireDeviceService.track({
        enclosure: this.trackModal.url, // 附件url
        content: this.trackModal.remark, // 跟进内容
        type: 13, // 业务类型 // todo 跟进类型
        relationInformation: this.trackModal.id, // 订单id
      }).then((result: any) => {
        if (result.code === 0) {
          this.nzMessageService.success('操作成功');
          this.trackModal = {
            visible: false,
            loading: false,
            orderNum: '',
            url: '',
            remark: '',
            file: [],
          };
        } else {
          this.trackModal.loading = false;
          this.nzMessageService.error('操作失败');
        }
      });
    } else {
      this.trackModal = {
        visible: false,
        loading: false,
        orderNum: '',
        url: '',
        remark: '',
        file: [],
      };
    }
  }

  // 显示审核
  showCheckModal(data: any) {
    this.checkModal = {
      visible: true,
      id: data.id,
      deductWay: 0,
      imei: '',
      wper: 1,
      nper: data.nper, // 总期数
      firstRent: data.firstRent, // 首期租金
      totalRent: data.totalRent, // 总租金
    };
  }

  // 隐藏审核
  hideCheckModal() {
    this.checkModal = {
      visible: false,
      id: '',
      deductWay: 0,
      imei: '',
      wper: 1,
      nper: '', // 总期数
      firstRent: '', // 首期租金
      totalRent: '', // 总租金
    };
  }

  // 审核提交
  auditSubmit(id?: any) {
    if (!this.checkModal.imei) {
      this.nzMessageService.warning('请输入产品IMEI号');
      return;
    }
    this.hireDeviceService.orderAudit({
      id: this.checkModal.id,
      imei: this.checkModal.imei,
      deductWay: 0,
      wper: this.checkModal.wper,
    }).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.hideCheckModal();
        this.getTableData();
      }
    });
  }

  // 显示租户凭证
  showTenantModal(data: any) {
    this.tenantModal.userCertInfo = data.userCertification;
    // this.tenantModal.userCertInfo.userImage = this.tenantModal.userCertInfo.userImage ? this.tenantModal.userCertInfo.userImage.replace('http:', 'https:') : '';
    // this.tenantModal.userCertInfo.userBackImage = this.tenantModal.userCertInfo.userBackImage ? this.tenantModal.userCertInfo.userBackImage.replace('http:', 'https:') : '';
    this.tenantModal.visible = true;
  }

  downloadImage(imgSrc: any) {
    this.httpClient.get(imgSrc, {responseType: 'blob'}).subscribe(res => {
      console.log(res);
    });
  }

// 显示交易快照
  showSnapshot(id: any) {
    this.hireDeviceService.getSnapshot(id).then((res: any) => {
      if (res.code === 0) {
        this.snapshotModal.visible = true;
        this.snapshotModal.data = res.data;
        this.snapshotModal.data.goods.imgs = JSON.parse(this.snapshotModal.data.goods.imgs);
        this.snapshotModal.data.goods.goodsInfo = JSON.parse(this.snapshotModal.data.goods.goodsInfo);
        this.snapshotModal.data.goods.leaseExplainImg = JSON.parse(this.snapshotModal.data.goods.leaseExplainImg);
        console.log(res);
      }
    });
  }

  // 订单导出
  export() {
    this.nzModalService.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的订单数据，为了导出速度请尽可能控制导出范围。确定导出？',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        const res: any = await this.hireDeviceService.exportOrder({
          orderNum: this.query.orderNum, // 订单流水号
          title: this.query.title, // 商品标题
          goodsName: this.query.goodsName, // 商品名称
          status: this.query.status, // 订单状态 多个用逗号隔开
          planId: this.query.planId.join(','), // 租赁方案 多个用逗号隔开
          rper: this.query.rper.join(','), // 租期 多个用逗号隔开
          user: this.query.user, // 用户信息
          beginTime: this.datePipe.transform(this.query.date[0], 'yyyy-MM-dd') || '', // 下单开始时间
          endTime: this.datePipe.transform(this.query.date[1], 'yyyy-MM-dd') || '', // 下单结束时间
        });
        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '订单信息');
        } else {
          this.nzMessageService.error('导出失败');
        }
      },
      nzCancelText: '关闭'
    });
  }

  // 发货
  deliverGoods() {
    if (!this.deliverGoodsModal.expressCode) {
      this.nzMessageService.warning('请选择物流公司');
      return;
    }
    if (this.deliverGoodsModal.expressCode !== 'SF' && !this.deliverGoodsModal.expressNum) {
      this.nzMessageService.warning('请输入物流单号');
      return;
    }
    // if (!this.deliverGoodsModal.imei) {
    //   this.nzMessageService.warning('请输入产品IMEI号');
    //   return;
    // }
    this.hireDeviceService.deliverGoods({
      expressName: this.deliverGoodsModal.expressName,
      expressCode: this.deliverGoodsModal.expressCode,
      expressNum: this.deliverGoodsModal.expressCode === 'SF' ? '' : this.deliverGoodsModal.expressNum,
      // imei: this.deliverGoodsModal.imei,
      id: this.deliverGoodsModal.id,
      expressVas: this.deliverGoodsModal.expressVas,
    }).then((res: any) => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.hideDeliverGoodsModal();
        this.getTableData();
      }
    });
  }
}
